/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.krossk.servlets;

import br.com.krossk.dao.UsuarioDAO;
import br.com.krossk.model.Usuario;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author HP DV5
 */
public class LoginServlet extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=windows-1252");
        boolean status = Boolean.parseBoolean(request.getParameter("value"));
        if(status){
            UsuarioDAO uDAO = new UsuarioDAO();
            Usuario u;
            String msg = "";

            //Parametros da tela de Login
            //nomeUsuario -> nome de usuario cadastrado (email)
            //senha -> senha para o nome de usuario utilizado

            String nomeUsuario = request.getParameter("usuario");
            String senha = request.getParameter("senha");

            nomeUsuario = nomeUsuario.trim();

            u = uDAO.getByEmail(nomeUsuario);

            // Valida usuario
            if(u == null)
            {
                //Usuario não encontrado na base
                msg = "Nome de usuário e senha inválidos.";
                doDispatcher(request, msg, response);
            }
            else
                if(u.getSenha().equals(senha))
                {
                    // Usuario Válido, ação: armazenar o objeto do usuario em uma Session
                    HttpSession session = request.getSession();
                    session.setAttribute("usuario", u);
                    response.sendRedirect("home.jsp");
                }
                else
                {
                    // Usuario Inválido, ação: retornar a tela inicial com mensegem de erro
                    msg = "Senha inválida.";
                    doDispatcher(request, msg, response);
                }
        }else{
            doLogout(request, response);
        }

    }
    public void doLogout(HttpServletRequest request, HttpServletResponse response) throws IOException{
        HttpSession session = request.getSession();
        session.setAttribute("usuario", null);
        session.setMaxInactiveInterval(0);
        response.sendRedirect("index.jsp");
    }

    protected void doDispatcher(HttpServletRequest request, String msg, HttpServletResponse response) throws IOException, ServletException {
        RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
        request.setAttribute("mensagem", msg);
        rd.forward(request, response);
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
